import { src, dest, watch, series, parallel } from 'gulp';
import dartSass from 'sass';
import gulpSass from 'gulp-sass';
import changedInPlace from 'gulp-changed-in-place';
import template from 'gulp-art-template4';
import webserver from 'gulp-webserver';
import rename from 'gulp-rename';
import clean from 'gulp-clean';
import gulpif from 'gulp-if';
import replace from 'gulp-replace';
import prettify from 'gulp-html-prettify';
import path from 'path';
import { readdir, readFile } from 'node:fs/promises';
const sass = gulpSass(dartSass);

const output = 'build';
const componentSrc = './src/**/component/**/*.art';
const layoutSrc = './src/**/layout/**/*.art';
const htmlSrc = './src/**/*.art';
const staticSrc = `./src/**/*.{png,jpg,gif,js,ttf,woff,woff2,css}`;
const scssSrc = './src/**/*.scss';
const dataJson = './data/**/*.json';
const configServer = {
	livereload: true, //文件修改自动刷新
	host: '192.168.1.241', //域名前缀
	port: 9860, //端口
	open: '/view/desktop/index.html', //要打开的页面，指向打包成功后的文件目录
	directoryListing: true,
	proxies: [
		{
			source: '/api',
			target: 'http://localhost:8000/',
		},
	],
};
let tplData = {};
function watchTask() {
	watch(componentSrc, html);
	watch(layoutSrc, html);
	watch(htmlSrc, html);
	watch(scssSrc, scss);
	watch(staticSrc, copy);
	watch(dataJson, series(readAndStoreJsonFiles, html))
}
// 定义 json 文件的目录

// 功能函数：异步读取目录下所有json文件，然后存储到对象中
async function readAndStoreJsonFiles(cb) {
	const directoryPath = path.join(__dirname, '/data/');
	let results = {};
	try {
		const files = await readdir(directoryPath);
		for (const file of files) {
			if (path.extname(file).toLowerCase() === ".json") {
				// 读取并解析 json 文件
				const filePath = path.join(directoryPath, file);
				const getJson = await readFile(filePath, 'utf8');
				if (!getJson) {
					continue;
				}
				const data = JSON.parse(getJson);
				// 使用文件名（去除扩展名）作为 key
				const key = path.basename(file, ".json");
				results[key] = data;
			}
		}
		tplData = results
	} catch (err) {
		console.error('文件报错：', err);
	}
	cb();
}
//打包HTML
function html() {
	return src([htmlSrc])
		.pipe(
			template(
				tplData,
				{
					extname: '.art', // some art-template options
				},
				{
					ext: '.html',
				}
			)
		)
		.pipe(replace(/\/build/g, ''))
		.pipe(
			changedInPlace({
				firstPass: true,
			})
		)
		.pipe(prettify())
		.pipe(dest(output));
}
//拷贝其他资源
function copy() {
	return src(staticSrc, { encoding: false })
		.pipe(
			changedInPlace({
				firstPass: true,
			})
		).pipe(gulpif('*.css', replace(/\/build/g, '')))
		.pipe(dest(output));
}
//清理文件
function clearFile() {
	return src(output, { allowEmpty: true }).pipe(clean({ force: true }));
}
//打包scss
function scss() {
	return src([scssSrc])
		.pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError))
		.pipe(
			changedInPlace({
				firstPass: true,
			})
		)
		.pipe(
			rename(function (path) {
				path.dirname = path.dirname.replace(/scss/, 'css'); // 直接在dirname中替换scss为css
			})
		)
		.pipe(dest(output));
}

//开启本地服务
function server() {
	return src(output).pipe(webserver(configServer));
}
export default series(clearFile, parallel(scss, copy), series(readAndStoreJsonFiles, html), series(server, watchTask));
